#pragma once
#include "Socket.hpp"
#include <sys/epoll.h>
#include <cstdlib>
using namespace SocketModule;
#include "Commn.hpp"

const int gdefaultfd = -1;
class EpollServer
{
public:
    EpollServer(uint16_t port)
        : _port(port),
          _listen_socket(std::make_shared<Tcpsocket>()),
          _isrunning(false),
          _epfd(gdefaultfd)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpserver(_port);
        _epfd = ::epoll_create(256); // 这里的参数随便给 > 0
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_create error";
            Die(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::ERROR) << "epoll_create success: " << _epfd;

        struct epoll_event events;
        events.events = EPOLLIN;
        events.data.fd = _listen_socket->FD();                                  // 为什么要设置这个呢?
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listen_socket->FD(), &events); // 这里我们只进行读文件描述符检测
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            Die(EPOLL_CTL_ERR);
        }
        LOG(LogLevel::ERROR) << "epoll_ctl success";
    }

    void Loop()
    {
        _isrunning = true;
        int timeout = 0;
        while (_isrunning)
        {
            int n = epoll_wait(_epfd, _revents, 64, timeout);
            switch (n)
            {
            case -1:
                std::cout << "读取异常" << std::endl;
                break;
            case 0:
                std::cout << "time out...." << std::endl;
                break;
            default:
                std::cout << "有fd就绪了!!" << std::endl;
                // Dispatcher(n); // 根据文件描述符，分配不同的模块
                break;
            }
        }
        _isrunning = false;
    }
    void Dispatcher(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            int event = _revents[i].events;
            int fd = _revents[i].data.fd; // 这就是为什么上面要初始化化这个的原因。
            if (fd == _listen_socket->FD())
            {
                if (event & EPOLLIN)
                {
                    // 进行accept事件
                    Acceptor();
                }
            }
            else
            {
                if (event & EPOLLIN)
                {
                    // IO事件，这里我们只处理读
                    ReadIo(fd);
                }
            }
        }
    }
    void Acceptor()
    {
        InetAddr client;
        // memset(&client, 0, sizeof(client)); 注意这里不要清空，不然我们初始化的 Len大小就是0了，此时IP和端口显示不了
        int newfd = _listen_socket->accpetor(&client);
        if (newfd > 0)
        {
            std::cout << "有新的连接来了, 新的连接为: " << client.Addr() << std::endl;
            struct epoll_event events;
            events.events = EPOLLIN;
            events.data.fd = newfd;                                  
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD,newfd, &events); // 添加到红黑树节点当中让epoll帮我们等待
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                Die(EPOLL_CTL_ERR);
            }
            LOG(LogLevel::ERROR) << "epoll_ctl success";
        }
        else
        {
            LOG(LogLevel::ERROR) << "access error";
            return;
        }
    }
    void ReadIo(int fd)
    {
        char buffer[1024];
        int n = ::recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            LOG(LogLevel::DEBUG) << buffer;
            std::string message = "echo server# ";
            message += buffer;
            ::send(fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0) // 此时说明有连接对端退出了
        {
            LOG(LogLevel::DEBUG) << "client Quit: " << fd;
            //这里需要注意，epoll要求当我们把fd删除的时候，需要保证这个fd是合法的!!
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL,fd, nullptr); // 如果是删除的话，events直接填写空指针
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                Die(EPOLL_CTL_ERR);
            }
            LOG(LogLevel::ERROR) << "epoll_ctl success";
            ::close(fd); //所以我们在epoll_ctl删除红黑树节点之后才来关闭文件描述符
        }
        else
        {
            LOG(LogLevel::ERROR) << "读取异常";
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL,fd, nullptr); // 如果是删除的话，events直接填写空指针
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                Die(EPOLL_CTL_ERR);
            }
            LOG(LogLevel::ERROR) << "epoll_ctl success";
            ::close(fd); //所以我们在epoll_ctl删除红黑树节点之后才来关闭文件描述符
        }
    }
    ~EpollServer() {}
    
private:
    uint16_t _port;
    bool _isrunning;
    std::shared_ptr<Socket> _listen_socket;
    int _epfd;                       // 模型的文件描述符
    struct epoll_event _revents[64]; // 这里直接硬编码了
};